package com.cbtx.tablet.service

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import com.blankj.utilcode.util.AppUtils
import com.cbtx.tablet.bean.ScreenSaverBean
import com.cbtx.tablet.ui.AppManager
import com.cbtx.tablet.ui.MainActivity
import com.cbtx.tablet.ui.PlayActivity
import com.cbtx.tablet.ui.StartActivity
import java.io.Serializable


/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/7 5:11 PM
 * desc   :
 */
class TaskService : Service() {

    companion object {
        var activityTouchTime: Long = 0
    }

    private var mHandler: Handler? = null

    override fun onCreate() {
        super.onCreate()
        activityTouchTime = System.currentTimeMillis()
        if (mHandler == null) {
            mHandler = Handler()
            startTime()
        } else {
            mHandler!!.removeCallbacksAndMessages(null)
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    private fun startTime() {
        mHandler!!.postDelayed(Runnable {
            val time2 = System.currentTimeMillis() - activityTouchTime
            val bannerItemList = ArrayList<ScreenSaverBean>()
            bannerItemList.addAll(MainActivity.advBannerList)

            // 当前是其他应用正在使用中，防止回到首页后，直接进入屏保页面
            if (!AppUtils.isAppForeground()) {
                activityTouchTime = System.currentTimeMillis()
            }
            // 十分钟进入屏保(必须是8+5的app处于前台)
            if (time2 >= 1000 * 60 * 10 && bannerItemList.size > 0 && AppUtils.isAppForeground()) {
                activityTouchTime = System.currentTimeMillis()
                val activity = AppManager.currentActivity() ?: return@Runnable
                if (activity !is PlayActivity && activity is MainActivity) {
                    val intent = Intent(activity, PlayActivity::class.java)
                    intent.putExtra("bannerItemList", bannerItemList as Serializable?)
                    activity.startActivity(intent)
                }
            }
            startTime()
        }, 2 * 1000.toLong())
    }
}